package com.bt.lms.ui.action.teaching.plan.query;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.TeachingPlanBizTypeConstant;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.ReqMsg;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.TableView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author 李舒淇
 */
public class LastLabAction implements EventHandler {

    public TableView tableView;

    public int current;



    public LastLabAction(TableView tableView, Integer current) {
        this.tableView = tableView;
        this.current=current;
    }

    @Override
    public void handle(Event event) {


        UnbindPackage unbindP = new UnbindPackage();

        //1、组包
        Page page = new Page();
        page.setCurrent(current-1);
        String jsonStr = JSON.toJSONString(page);
        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(TeachingPlanBizTypeConstant.PLAN_QUERY);
        reqMsg.setData(jsonStr);
        byte[] msgByte = reqMsg.toBytes();

        //2、组网
        String serverip = "127.0.0.1";
        int port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //3、发送消息
        OutputStream out = null;
        try {
            out = socket.getOutputStream();
            out.write(msgByte);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //4、接收消息
        byte[] acceptBuffer = new byte[2100];
        try {
            InputStream in = socket.getInputStream();
            in.read(acceptBuffer);
            in.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        unbindP.unbindPackage(acceptBuffer, tableView);


    }
}
